package com.jsbb.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsbb.common.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author w
 * @date 2021-03-05
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @ExceptionHandler(value = Exception.class)
    public Message exceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
        Message message = new Message();
        message.setCode("0001");
        message.setMessage("失败");
        log.error("请求地址={},接口响应={},异常={}", request.getRequestURL(), objectMapper.writeValueAsString(message), exception);
        return message;
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Message methodNotSupportHandle(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        log.error("请求地址={},异常={}", request.getRequestURL(), e);
        return Message.tips("不支持的请求方法");
    }

    @ExceptionHandler(value = {ServiceException.class})
    public Message serviceExceptionHandler(HttpServletRequest request, ServiceException serviceException) throws JsonProcessingException {
        Message message = new Message(serviceException.getCode(), serviceException.getMsg(), null);
        log.error("请求地址={},接口响应={},异常={}", request.getRequestURL(), objectMapper.writeValueAsString(message), serviceException);
        return message;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Message methodArgumentNotValidHandler(HttpServletRequest request, MethodArgumentNotValidException exception) throws Exception {
        StringBuffer sb = new StringBuffer();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            sb.append(error.getField()).append(error.getDefaultMessage()).append(";");
        }
        Message message = Message.tips("参数验证失败");
        message.setData(sb);
        log.error("请求地址={}。接口响应={}", request.getRequestURL(), objectMapper.writeValueAsString(message));
        return message;
    }
}
